package common

import (
	"time"
	"tt_erp/model"

	"github.com/dgrijalva/jwt-go"
)

type Claims struct {
	UserId uint
	jwt.MapClaims
}

var jwtkey = []byte("erp-secret-key")

// 获取token
func GenerateToken(user model.User) (string, error) {

	claims := Claims{
		UserId: user.ID,
		MapClaims: jwt.MapClaims{
			"ExpiresAt": time.Now().Add(24 * time.Hour), //到期时间
			"IssuedAt":  time.Now().Unix(),              //签发日期
			"Issuer":    "tt_erp",                       //发放人
			"Subject":   "tt_token",                     //主题
		},
	}

	// 使用 HS256 签名方法
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	// 生成 JWT Token
	signedToken, err := token.SignedString(jwtkey)

	if err != nil {
		return "", err
	}

	return signedToken, nil
}

// 解析token
func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
	claims := &Claims{}

	token, err := jwt.ParseWithClaims(tokenString, claims, func(t *jwt.Token) (interface{}, error) {
		return jwtkey, nil
	})

	return token, claims, err
}
